/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="main-content" v-if="!!chooseId">
    <div class="content-title" style="position:relative;">
      <div style="position:absolute;right:10PX;top:5PX;border: 0PX solid red;">
        <el-button class="btn" type="primary" size="medium" @click="onGenerateClick">{{$t('openatc.area.areaOptimize')}}</el-button>
        <el-button class="btn" type="primary" size="medium" @click="onDownloadClick" style="margin-left:10PX;">{{$t('openatc.area.downloadPattern')}}</el-button>
      </div>
      <ContentTitle ref="contentTitle"></ContentTitle>
    </div>
    <div class="content-main1">
      <div style='position: absolute;right:10PX;top:5PX;border:0PX solid red;z-index:200001;'>
        <el-button class="btn" type="text" icon="el-icon-edit" size="medium" v-if="activeName === 'first'" @click="onAddClick">{{$t('openatc.area.editOptimizeRoute')}}</el-button>
        <el-button class="btn" type="text" icon="el-icon-plus" size="medium" v-if="activeName === 'second'" @click="onAddClick" style="margin-left:10PX;">{{$t('openatc.area.addOptimizeIntersection')}}</el-button>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick" @edit="handleTabsEdit" :before-leave="beforeLeave" class="tabs">
        <el-tab-pane :label="$t('openatc.area.route')" name="first" style="height:100%;width:100%;border:0PX solid red;">
          <GreenWaveOptimize ref="greenWaveOptimize" v-show="false" :areaId="chooseId" @onRouteChange="onRouteChange"></GreenWaveOptimize>
          <RouteOptimize ref="routeOptimize" :isShowOperation="isShowOperation" :routesList="routeData"></RouteOptimize>
        </el-tab-pane>
        <!-- <el-tab-pane :label="$t('openatc.greenwaveoptimize.device')" name="second" style="height:100%;width:100%;border:0PX solid red;">
          <PatternTable ref="patterntable" :areaId="chooseId" @onNewPatternListChange="onNewPatternListChange"/>
        </el-tab-pane> -->
        <PatternTable v-show="false" ref="patterntable" :areaId="chooseId" @onNewPatternListChange="onNewPatternListChange"/>
      </el-tabs>
    </div>
    <ChoseIntersection ref="choseIntersection" @onSureClick="onSureClick"></ChoseIntersection>
    <ChoseRoute ref="choseRoute" @onSureClick="onSureClick"></ChoseRoute>
    <Messagebox :visible="messageboxVisible" :text="$t('openatc.greenwaveoptimize.confirmdownloadpattern')" @cancle="cancle" @ok="ok"/>
  </div>
</template>

<script>
import AreaApi from '../../../api/area'
import ChoseRoute from '../../../components/ChoseRoute/index.vue'
import ChoseIntersection from '../../../components/ChoseIntersection/index.vue'
import ContentTitle from './ContentTitle.vue'
import GreenWaveOptimize from '../index.vue'
import RouteOptimize from '../../RouteOptimize/index.vue'
import PatternTable from '../pattern/patternTable.vue'
import PlanChart from '../pattern/planChart/index.vue'
import Messagebox from '../../../components/MessageBox/index.vue'
import { getMessageByCode } from '../../../utils/responseMessage'
export default {
  name: 'PlanContent1',
  data () {
    return {
      isShowOperation: false,
      generateFlag: false,
      area: {},
      devList: [],
      isolate: [],
      activeName: 'first',
      activeName2: 'second',
      maskVisible: false, // 引导遮罩层是否显示
      configurationVisible: false, // 配置界面是否显示
      messageboxVisible: false, // 关闭界面二期确认弹窗是否显示
      addNum: 0,
      mock: [],
      routeData: [], // 单个协调路线的全部信息
      patternList: [],
      phaseList: [],
      greenwave: []
    }
  },
  components: {
    RouteOptimize,
    ChoseRoute,
    ChoseIntersection,
    ContentTitle,
    GreenWaveOptimize,
    PatternTable,
    PlanChart,
    Messagebox
  },
  props: {
    schemeData: {
      type: Array
    },
    step: {
      type: Boolean
    },
    zIndexObj: {
      type: Object
    },
    chooseId: {
      type: Number
    }
  },
  watch: {
    schemeData: {
      handler: function (val) {
        if (val && !val.length && this.step) {
          this.maskVisible = true
          // 模拟一次手动点击，触发tip显示
          this.$refs.editbtn.click()
        }
      },
      deep: true
    }
  },
  mounted () {
    this.getRouteInfo()
  },
  methods: {
    cancle () {
      this.messageboxVisible = false
    },
    ok () {
      this.messageboxVisible = false
      this.handleDownload()
    },
    Download () {
      this.messageboxVisible = true
    },
    handleClick (tab, event) {
      if (tab.name === 'first') {
        this.refreshChart()
      }
    },
    refreshChart () {
      let patterntable = this.$refs.patterntable
      let newPatternList = patterntable.newPatternList
      for (let pattern of this.patternList) {
        let agentid = pattern.agentid
        let newPattern = newPatternList.filter(npl => npl.agentid === agentid)[0]
        let patternId = newPattern.patternId
        let currPatternList = pattern.feature.patternList
        let currPattern
        if (Array.isArray(currPatternList)) {
          currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
        } else {
          currPattern = currPatternList
        }
        currPattern.cycle = newPattern.cycle
        currPattern.offset = newPattern.offset
      }
      this.handlePlanChart()
    },
    handleEdit () {
      if (this.maskVisible && this.addNum <= 1) {
        if (this.addNum === 1) {
          this.maskVisible = false
        }
        this.addNum++
      }
      if (!this.maskVisible) {
        // 获取单个协调路线的全部信息
        // (弹窗取消后，应重新获取静态数据，此处采取中间变量法重新赋值，以触发watch能监听到routeData变化，给弹窗内共有变量configData重新赋值)
        const lastRouteData = JSON.parse(JSON.stringify(this.routeData))
        this.routeData = []
        this.routeData = lastRouteData
        this.configurationVisible = true
      }
    },
    uploadAreaPattern (list) {
      if (this.chooseId === 0) return
      AreaApi.uploadAreaPattern(this.chooseId).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        let devList = res.data.data.devs
        console.log(devList)
        for (let dev of list) {
          let agentid = dev.agentid
          let devFearure = devList.filter(item => item.agentid === agentid)[0]
          let patternList = devFearure.patternList
          let phaseList = devFearure.phaseList
          dev.patternList = patternList
          dev.phaseList = phaseList
          let curPattern = patternList[0]
          let offset = curPattern.offset
          let cycle = curPattern.cycle
          dev.offset = offset
          dev.cycle = cycle
          console.log(devFearure)
        }
        // for (let dev of devsList) {
        //   let agentid = dev.agentid
        //   let feature = dev.feature
        //   let patternList = feature.patternList
        // }
        // let contentTitle = this.$refs.contentTitle
        // contentTitle.init(area, list)
        // this.getAllPatternOfRoute() // 获取该路线的所有方案
      })
    },
    getRouteInfo () {
      if (this.chooseId === 0) return
      AreaApi.getSingleArea(this.chooseId).then(res => {
        if (!res.data.success) {
          if (res.data.code === '4003') {
            let agentid = res.data.data.agentid
            this.$message.error(this.$t('openatc.greenwaveoptimize.device') + agentid + this.$t('openatc.greenwaveoptimize.notonline'))
            return
          }
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        let area = res.data.data
        this.area = area
        this.routeData = area.routes
        this.isolate = area.isolate
        this.$refs.greenWaveOptimize.planData = this.routeData
        this.$refs.patterntable.newPatternList = this.isolate
        let list = []
        list = this.getDevList()
        this.devList = list
        let contentTitle = this.$refs.contentTitle
        contentTitle.init(area, list)
        this.getAllPatternOfRoute() // 获取该路线的所有方案
      })
    },
    getDevList () {
      let list = []
      for (let route of this.routeData) {
        let devs = route.devs
        for (let dev of devs) {
          let filterDev = list.filter(item => item.agentid === dev.agentid)
          if (!filterDev || filterDev.length === 0) {
            list.push(dev)
          }
        }
      }
      for (let dev of this.isolate) {
        let filterDev = list.filter(item => item.agentid === dev.agentid)
        if (!filterDev || filterDev.length === 0) {
          list.push(dev)
        }
      }
      return list
    },
    getReqData () {
      // let patterntable = this.$refs.patterntable
      // let newPatternList = patterntable.newPatternList
      // let greenWaveOptimize = this.$refs.greenWaveOptimize
      // console.log(newPatternList)
      // console.log(greenWaveOptimize)
      // console.log(greenWaveOptimize.routeData)
      // console.log(this.routeData)
      // console.log(this.patternList)
      let list = this.getDevList()
      console.log(list)
      for (let pattern of this.patternList) {
        let agentid = pattern.agentid
        let newPattern = list.filter(npl => npl.agentid === agentid)[0]
        // let patternId = newPattern.id
        let patternId = newPattern.patternid
        let currPatternList = pattern.feature.patternList
        let currPattern
        if (Array.isArray(currPatternList)) {
          currPattern = currPatternList.filter(cpl => cpl.id === patternId)[0]
        } else {
          currPattern = currPatternList
        }
        currPattern.cycle = newPattern.cycle
        currPattern.offset = newPattern.offset
      }
      let targetPatternList = JSON.parse(JSON.stringify(this.patternList))
      for (let patternItem of targetPatternList) {
        let agentid = patternItem.agentid
        let newPattern = list.filter(npl => npl.agentid === agentid)[0]
        let patternId = newPattern.patternid
        patternItem.feature.patternList = patternItem.feature.patternList.filter(cpl => cpl.id === patternId)
        patternItem.feature.phaseList = this.phaseList.filter(cpl => cpl.agentid === agentid)[0].feature.phaseList
      }
      console.log('targetPatternList', targetPatternList)
      return targetPatternList
    },
    handleDownload () {
      this.getReqData()
      let param = {}
      param.devs = this.patternList
      AreaApi.downloadAreaRoutes(param).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.generateFlag = false
        this.$alert(this.$t('openatc.greenwaveoptimize.planissuedsucc'), { type: 'success' })
      })
    },
    onGenerateClick () {
      // let routeData = this.editableTabs[this.currentIndex]
      // // check
      // let check = this.checkData([routeData], false)
      // if (!check) {
      //   return false
      // }
      // let msg = this.$t('openatc.greenwaveoptimize.algorithmEngineOptimization')
      // const loading = this.$loading({
      //   lock: true,
      //   text: msg,
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0, 0, 0, 0.7)'
      // })
      // setTimeout(() => {
      //   loading.close()
      //   this.handleCreate()
      // }, 1000)
      this.doRouteOptimize()
    },
    doRouteOptimize () {
      let routeOptimize = this.$refs.routeOptimize
      if (routeOptimize) {
        routeOptimize.onGenerateClick()
      }
    },
    doRouteDownload () {
      let routeOptimize = this.$refs.routeOptimize
      if (routeOptimize) {
        routeOptimize.onDownloadClick()
      }
    },
    onDownloadClick () {
      this.doRouteDownload()
    },
    handleCreate () {
      // check
      let contentTitle = this.$refs.contentTitle
      let keyrouteid = contentTitle.keyrouteid
      if (!keyrouteid) {
        this.$message.warning(this.$t('openatc.area.keyrouteidCheck'))
        return false
      }
      let patternList = this.getReqData()
      let param = {
        'cycle': 0,
        'id': 0,
        'isolate': [],
        'keyintsid': '',
        'masterroute': {},
        'name': '',
        'optstrategy': 0,
        'opttype': 0,
        'routes': []
      }
      param.cycle = Number(contentTitle.cycle)
      param.id = contentTitle.areaId
      param.keyintsid = contentTitle.keyintsid
      param.name = this.area.name
      let optstrategy = contentTitle.optstrategy
      param.optstrategy = optstrategy === 'static' ? 0 : 1
      param.opttype = optstrategy === 'static' ? 0 : 1
      let isolate = []
      let masterroute = []
      let routes = []
      isolate = this.isolate.map(item => {
        return {
          agentid: item.agentid
        }
      })
      masterroute = this.routeData.filter(item => item.id === keyrouteid)[0]
      masterroute.devs = masterroute.devs.map(item => {
        let feature = patternList.filter(pattern => pattern.agentid === item.agentid)[0].feature
        let res = {
          ...item,
          feature: feature
        }
        return res
      })
      routes = this.routeData.filter(item => item.id !== keyrouteid)
      for (let route of routes) {
        let devs = route.devs
        for (let dev of devs) {
          let feature = patternList.filter(pattern => pattern.agentid === dev.agentid)[0].feature
          dev.feature = feature
        }
      }
      param.masterroute = masterroute
      param.routes = routes
      param.isolate = isolate
      AreaApi.generateAreaPattern(param).then(res => {
        if (!res) {
          this.$message.error(this.$t('openatc.bottleneckcontrol.controlfailed'))
          return
        }
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.generateFlag = true
        this.$message.success(this.$t('openatc.common.operationsuccess'))
        let area = res.data.data
        let newRouteData = area.routes
        for (let route of this.routeData) {
          for (let newRoute of newRouteData) {
            if (route.id === newRoute.id) {
              route.devs = newRoute.devs
              route.greenwave = newRoute.greenwave
            }
          }
        }
        this.area.keyintsid = area.keyintsid
        this.area.cycle = area.cycle
        this.isolate = area.isolatedcrosses
        let list = []
        for (let route of this.routeData) {
          for (let dev of route.devs) {
            list.push(dev)
          }
        }
        for (let dev of this.isolate) {
          if (!dev.patternid) {
            let patternid = dev.feature.patternList[0].id
            dev.patternid = patternid
          }
          list.push(dev)
        }
        this.patternList = list
        this.$refs.patterntable.newPatternList = this.isolate
        this.handlePatternTable()
        this.handlePlanChart()
        // this.handleMaskVisible()
        let contentTitle = this.$refs.contentTitle
        contentTitle.init(this.area, list)
      })
    },
    closeDrawer (isRefresh) {
      this.configurationVisible = false
      if (isRefresh === 'refresh') {
        this.$emit('resetContentComponent')
      }
    },
    clickMask () {
      this.maskVisible = false
    },
    getAllPatternOfRoute () {
      if (this.chooseId === 0) return
      AreaApi.uploadAreaPattern(this.chooseId).then(res => {
        if (!res.data.success) {
          let agentid = res.data.data.agentid
          let commomMsg = this.$t('openatc.greenwaveoptimize.device') + agentid
          let data = res
          let parrenterror = getMessageByCode(data.data.code, this.$i18n.locale)
          if (data.data.data) {
            // 子类型错误
            let childErrorCode = data.data.data.errorCode
            if (childErrorCode) {
              let childerror = getMessageByCode(data.data.data.errorCode, this.$i18n.locale)
              this.$message.error(parrenterror + ',' + childerror + ',' + commomMsg)
            }
          } else {
            this.$message.error(parrenterror + ',' + commomMsg)
          }
          return
        }
        this.patternList = res.data.data.devs
        // this.handlePlanChart()
        this.getAllPhaseOfRouter() // 获取改路线的所有相位
      })
    },
    getAllPhaseOfRouter () {
      if (this.chooseId === 0) return
      AreaApi.uploadAreaPhase(this.chooseId).then(res => {
        if (!res.data.success) {
          if (res.data.code === '4003') {
            let agentid = res.data.data.agentid
            this.$message.error(this.$t('openatc.greenwaveoptimize.device') + agentid + this.$t('openatc.greenwaveoptimize.notonline'))
            return
          }
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.phaseList = res.data.data.devs
        this.handlePatternTable()
        this.handlePlanChart()
        this.handleMaskVisible()
      })
    },
    handlePatternTable () {
      let patterntable = this.$refs.patterntable
      patterntable.onPatternTable(this.isolate, this.patternList, this.phaseList)
    },
    handlePlanChart () {
      let planchart = this.$refs.greenWaveOptimize
      planchart.onPlanChart(this.routeData, this.patternList, this.greenwave, this.phaseList)
    },
    handleMaskVisible () {
      // 数据为空，显示蒙层
      if (this.patternList && !this.patternList.length && this.step) {
        this.maskVisible = true
        // 模拟一次手动点击，触发tip显示
        this.$refs.editbtn.click()
      }
    },
    onRouteChange (routeList) {
      // 接下来此行测试是否需要删除
      this.routeData = routeList
      let list = this.getDevList()
      let contentTitle = this.$refs.contentTitle
      contentTitle.doSynchronize(list)
    },
    onNewPatternListChange (newPatternList) {
      // this.refreshChart()
      this.isolate = newPatternList
      let list = this.getDevList()
      let contentTitle = this.$refs.contentTitle
      contentTitle.doSynchronize(list)
    },
    updateAreaRoutes (data, components, fullList) {
      AreaApi.updateAreaRoutes(data).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        if (components) {
          components.planData = fullList
        }
        this.$message({
          message: this.$t('openatc.common.addsuccess'),
          type: 'success',
          duration: 1 * 1000,
          onClose: () => {
            // this.$emit('refresh')
            this.getRouteInfo()
          }
        })
      })
    },
    updateAreaDevs (data, components, fullList) {
      AreaApi.updateAreaDevs(data).then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        if (components) {
          components.newPatternList = fullList
          // 数据准备
          this.uploadAreaPattern(fullList)
        }
        this.$message({
          message: this.$t('openatc.common.addsuccess'),
          type: 'success',
          duration: 1 * 1000,
          onClose: () => {
            // this.$emit('refresh')
            this.getRouteInfo()
          }
        })
      })
    },
    onSureClick (list) {
      if (this.activeName === 'first') {
        let components = this.$refs.greenWaveOptimize
        // let planData = components.planData
        // let diffList = []
        // for (let item of list) {
        //   let flag = false
        //   for (let plan of planData) {
        //     if (item.id === plan.id) {
        //       flag = true
        //       break
        //     }
        //   }
        //   if (!flag) {
        //     diffList.push(item)
        //   }
        // }
        // let fullList = components.planData.concat(diffList)
        let fullList = list
        // 接口新增
        let idList = fullList.map(item => item.id)
        let reqData = {
          id: this.chooseId,
          list: idList
        }
        this.updateAreaRoutes(reqData, components, fullList)
        // components.planData = fullList
      } else {
        let components = this.$refs.patterntable
        // components.newPatternList = list
        let planData = components.newPatternList
        let diffList = []
        for (let item of list) {
          let flag = false
          for (let plan of planData) {
            if (item.agentid === plan.agentid) {
              flag = true
              break
            }
          }
          if (!flag) {
            diffList.push(item)
          }
        }
        let fullList = components.newPatternList.concat(diffList)
        // 接口新增
        let idList = fullList.map(item => item.agentid)
        let reqData = {
          id: this.chooseId,
          list: idList
        }
        this.updateAreaDevs(reqData, components, fullList)
        // components.newPatternList = fullList
      }
    },
    showDrawer () {
      this.handleEdit()
    },
    onAddClick () {
      // this.showDrawer()
      this.showComponents()
    },
    showComponents () {
      if (this.activeName === 'first') {
        let components = this.$refs.choseRoute
        components.show(this.routeData)
      } else {
        let components = this.$refs.choseIntersection
        components.show()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
